package com.czmh.etc.onlinepubsys.controller.ue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.onlinepubsys.constants.ue.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CarInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.request.ue.*;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICarInfoService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IObuService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.ue.UeHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/{version}/api/ue/bank")
@Api(tags = "4.3银行签约相关接口 -联合电子")
public class UeBankController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ICurrentContextService currentContextService;

    @Autowired
    private IObuService obuService;

    @Autowired
    private ICarInfoService carInfoService;

    @Autowired
    private IEtcApplyService etcApplyService;

    @PostMapping("/bankSigned")
    @ApiOperation("4.3.1提交银行四要素并获取验证码")
    public JSONResult bankSigned(@RequestBody BankSignedRequest req) {
        log.info("bankSigned:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.BANK_SIGNED, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }


    @PostMapping("/bankVerify")
    @ApiOperation("4.3.2校验验证码并确认签约")
    public JSONResult bankVerify(@RequestBody BankVerifyRequest req) {
        log.info("bankVerify:{}", JSON.toJSONString(req));
        req.setMarketer("");
        JSONResult result = new JSONResult();
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("该用户不在申办流程当中！");
            return result;
        }
        String token = redisUtil.queryUeToken();
        ApiResponse r = UeHttpUtil.post(BusinessType.BANK_VERIFY, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());

                //确认签约成功之后修改用户流程状态为4-签约成功
                currentContext.setState(4);
                currentContextService.update(currentContext);
                //同步更新车辆车牌和颜色入库，以及银行卡号信息入库
                ApplyInfo applyInfo = etcApplyService.get(currentContext.getApplyId());
                if(applyInfo != null){
                    applyInfo.setBankSignTime(new Date());
                    applyInfo.setState(1);
                    applyInfo.setVehicleColor(req.getVehicleColor() != null ? Integer.valueOf(req.getVehicleColor()) : null);
                    applyInfo.setVehiclePlate(req.getVehiclePlate());
                    applyInfo.setBankCardNo(req.getBankCard());
                    applyInfo.setVehicleType(1);
                    applyInfo.setBankCardType(1);
                    applyInfo.setBankSn(req.getSignType());
                    etcApplyService.update(applyInfo);
                }
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/noInsuranceOrderReview")
    @ApiOperation("4.3.3卡签自提接口")
    public JSONResult noInsuranceOrderReview(@RequestBody NoInsuranceOrderReviewRequest req) {
        log.info("noInsuranceOrderReview:{}", JSON.toJSONString(req));
        String token = redisUtil.queryUeToken();
        JSONResult result = new JSONResult();
        ApiResponse r = UeHttpUtil.post(BusinessType.NO_INSURANCE_ORDER_REVIEW, JSON.toJSONString(req), token);
        if (r != null && r.getSuccess()) {
            if (r.getSuccess()) {
                result.setRspData(r.getRspData());
                result.setMessage(r.getMsg());
                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                String jsonStr = currentContext.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if(jsonObject == null){
                    jsonObject = new JSONObject();
                }
                //noInsuranceOrderReview，1已提交
                jsonObject.put("noInsuranceOrderReview", "1");
                jsonObject.put("NoInsuranceOrderReviewRequest", req);
                currentContext.setJsonData(jsonObject.toJSONString());
                currentContextService.update(currentContext);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r != null ? r.getMsg() : "服务器开小差，请稍后再试！");
        }
        return result;
    }

    @PostMapping("/confirmActive")
    @ApiOperation("激活成功确认")
    public JSONResult confirmActive(@RequestBody ConfirmActiveRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表-用于保存该接口返回的短信版本号
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        log.info("confirmActive:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        //写OBU成功确认操作成功之后把对应的请求信息和返回信息入库
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext.getType() != 4) {
            result.setCode(JSONResult.FAIL);
            result.setMessage("流程信息类型不符合条件！");
            return result;
        }
        //判断是否在流程当中
        if (currentContext != null && currentContext.getState() == 4) {
            String jsonStr = currentContext.getJsonData();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            //判断是否提交订单
            if (jsonObject.getString("submitOrderStatus").equalsIgnoreCase("1")) {
                //是否激活状态
                boolean isActive = false;
                //查询已提交订单状态
                String token = redisUtil.queryUeToken();
                QueryOrderByVehicleRequest request = new QueryOrderByVehicleRequest();
                CarInfo etcCarInfo = carInfoService.get(currentContext.getCarId());
                if (etcCarInfo != null) {
                    request.setVehicleColor(String.valueOf(etcCarInfo.getVehColor()));
                    request.setVehiclePlate(etcCarInfo.getVehPlate());
                }
                log.info("queryOrderByVehicle:{}", JSON.toJSONString(request));
                ApiResponse r = UeHttpUtil.post(BusinessType.QUERY_ORDER_BY_VEHICLE, JSON.toJSONString(request), token);
                if (r != null && r.getSuccess()) {
                    if (r.getSuccess()) {
                        //查看是否激活
                        if (r.getRspData() != null) {
                            JSONObject object = JSON.parseObject(r.getRspData());
                            if (object != null && object.getString("object") != null) {
                                JSONArray jsonArray = JSON.parseArray(object.getString("object"));
                                if (jsonArray != null && jsonArray.size() > 0) {
                                    JSONObject jObject = (JSONObject) jsonArray.get(0);
                                    if (jObject.getString("order_status") != null
                                            && jObject.getString("order_status").equalsIgnoreCase("5")) {
                                        isActive = true;
                                        currentContext.setObuId(jObject.getString("obuid"));
                                        currentContext.setEtcCardNo(jObject.getString("cardno"));
                                    }
                                }
                            }
                        }

                    }
                }
                //激活成功之后执行的逻辑
                if (isActive) {
                    currentContextService.update(currentContext);
                    //按照铭创流程逻辑操作激活成功之后的操作
                    obuService.cmgActiveComplete(currentContext.getObuId(), req.getUserId());
                }
            }

        }
        return result;
    }

}
